package com.lfz.quality_effect.service.impl;


import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lfz.quality_effect.constant.LfzConstant;

import com.lfz.quality_effect.model.dto.CivilSettledRateDTO;
import com.lfz.quality_effect.model.dto.CollectionBalanceDTO;
import com.lfz.quality_effect.model.dto.TotalSettledRateDTO;
import com.lfz.quality_effect.model.entity.TCollectionBalance;
import com.lfz.quality_effect.mapper.TCollectionBalanceMapper;
import com.lfz.quality_effect.model.vo.EleScoreRankVO;
import com.lfz.quality_effect.model.vo.ScoreRankVO;
import com.lfz.quality_effect.service.TCollectionBalanceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lfz.quality_effect.utils.ExcelListener;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 收结存统计表 服务实现类
 * </p>
 *
 * @author Destiny
 * @since 2023-03-05
 */
@Slf4j
@Service
public class TCollectionBalanceServiceImpl extends ServiceImpl<TCollectionBalanceMapper, TCollectionBalance> implements TCollectionBalanceService {


    /**
     * 上传最高院数据
     * @param file
     * @param dataTime
     */
    @Override
    public void uploadCollectBalance(MultipartFile file, String dataTime) {

        QueryWrapper<TCollectionBalance> queryWrapper=new QueryWrapper();
        queryWrapper.eq("data_time",dataTime);
        ExcelListener listener = new ExcelListener();
        Integer count = this.getBaseMapper().selectCount(queryWrapper);
        if (null !=count  && count > 0){
            log.info("已存在最新的数据：{}",dataTime);
            return;
        }
        InputStream inputStream ;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //传入参数
        ExcelReader excelReader = new ExcelReader(inputStream, null, listener);
        //读取信息
        excelReader.read(new Sheet(1, 2, CollectionBalanceDTO.class));
        List<Object> objectList =listener.getDatas();

        List<TCollectionBalance> collectionBalanceList = new ArrayList<>();
        for (int i=0;i<objectList.size();i++){
            CollectionBalanceDTO collectionBalanceDTO = (CollectionBalanceDTO) objectList.get(i);

            TCollectionBalance collectionBalance =  this.getOne(new LambdaQueryWrapper<TCollectionBalance>()
                    .eq(TCollectionBalance::getDataTime,dataTime)
                    .eq(TCollectionBalance::getCourt, collectionBalanceDTO.getCourt()));
            if (collectionBalance == null){
                collectionBalance = new TCollectionBalance();
                BeanUtils.copyProperties(collectionBalanceDTO,collectionBalance);
                collectionBalance.setCreateTime(LocalDateTime.now());
            }
            // 民事
            BigDecimal civilUnsettled = new BigDecimal(collectionBalanceDTO.getCivilUnsettled());
            BigDecimal civilSettled = new BigDecimal(collectionBalanceDTO.getCivilSettled());
            BigDecimal civilTotal =   civilSettled.add(civilUnsettled);
            // 总案件
            BigDecimal totalSettled = new BigDecimal(collectionBalanceDTO.getTotalSettled());
            BigDecimal totalUnsettled = new BigDecimal(collectionBalanceDTO.getTotalUnsettled());
            BigDecimal total = totalSettled.add(totalUnsettled);
            // 民商事结案率=民事已结/民事已结+民事未结
            BigDecimal civilRate =  civilSettled.divide(civilTotal,4,BigDecimal.ROUND_UP);
            // 总结案率
            BigDecimal totalRate =  totalSettled.divide(total,4,BigDecimal.ROUND_UP);

            collectionBalance.setCivilSettledRate(civilRate);
            collectionBalance.setTotalSettledRate(totalRate);
            collectionBalance.setDataTime(dataTime);
            collectionBalanceList.add(collectionBalance);
        }
        this.saveBatch(collectionBalanceList);
    }

    /**
     * 上传全省质效详表
     * @param file
     * @param dataTime
     */
    @Override
    public void uploadCivilSettledRate(MultipartFile file, String dataTime) {

        ExcelListener listener = new ExcelListener();
        InputStream inputStream ;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //传入参数
        ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS,null, listener);
        Sheet sheet = new Sheet(1, 1, CivilSettledRateDTO.class);

        //读取信息
        excelReader.read(sheet);
        List<Object> objectList =listener.getDatas();


        ArrayList<TCollectionBalance> tList = new ArrayList<>();
        for (int i = 0; i < objectList.size(); i++) {
            CivilSettledRateDTO civilSettledRateDTO = (CivilSettledRateDTO) objectList.get(i);
            // 保留四位小数
            BigDecimal civilSettledRatio = civilSettledRateDTO.getCivilSettledRate().setScale(4, BigDecimal.ROUND_UP);
            Integer civilUnsettled  = civilSettledRateDTO.getCivilOld() + civilSettledRateDTO.getCivilNew() - civilSettledRateDTO.getCivilSettled();
            TCollectionBalance tCollectionBalance = new TCollectionBalance();

            if (civilSettledRateDTO.getCourt().equals("0.0")){
                tCollectionBalance.setCourt("合计");
            }else {
                tCollectionBalance.setCourt(civilSettledRateDTO.getCourt());
            }

            tCollectionBalance.setCivilSettled(civilSettledRateDTO.getCivilSettled());
            tCollectionBalance.setCivilUnsettled(civilUnsettled);
            tCollectionBalance.setCivilSettledRate(civilSettledRatio);
            tCollectionBalance.setCreateTime(LocalDateTime.now());
            tCollectionBalance.setDataTime(dataTime);

            tList.add(tCollectionBalance);

        }

        QueryWrapper<TCollectionBalance> wrapper = new QueryWrapper<>();
        wrapper.eq("data_time",dataTime);
        Integer count = this.getBaseMapper().selectCount(wrapper);

        wrapper.eq("court","合计");
        TCollectionBalance tCollectionBalance1 = this.getOne(wrapper);

        if (count != null && count > 0){
            // 更新
            log.info("已存在{}的数据",dataTime);
            for (TCollectionBalance tCollectionBalance : tList) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("court",tCollectionBalance.getCourt());
                paramMap.put("civilSettled",tCollectionBalance.getCivilSettled());
                paramMap.put("civilUnsettled",tCollectionBalance.getCivilUnsettled());
                paramMap.put("civilSettledRate",tCollectionBalance.getCivilSettledRate());
                paramMap.put("dataTime",dataTime);

                // 总结案率先插入 修改民商事结案率的同时也要插入  合计的数据
                if (tCollectionBalance.getCourt().equals("合计") && Objects.isNull(tCollectionBalance1)){
                    this.getBaseMapper().insert(tCollectionBalance);
                }

                this.getBaseMapper().updateCivilRate(paramMap);
            }

        }
        // 插入
        else {
            this.saveBatch(tList);
        }
    }


    /**
     * 上传总结案率
     * @param file
     * @param dataTime
     */
    @Override
    public void uploadTotalSettledRate(MultipartFile file, String dataTime) {

        ExcelListener listener = new ExcelListener();
        InputStream inputStream;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //传入参数
        ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS,null, listener);
        Sheet sheet = new Sheet(1, 1, TotalSettledRateDTO.class);

        //读取信息
        excelReader.read(sheet);
        List<Object> objectList =listener.getDatas();

        ArrayList<TCollectionBalance> tList = new ArrayList<>();
        for (int i = 0; i < objectList.size(); i++) {
            TotalSettledRateDTO totalSettledRateDTO = (TotalSettledRateDTO) objectList.get(i);
            BigDecimal totalSettledRate = totalSettledRateDTO.getTotalSettledRate().setScale(4,BigDecimal.ROUND_UP);
            TCollectionBalance tCollectionBalance = new TCollectionBalance();
            if (!totalSettledRateDTO.getCourt().equals("0.0")){
                tCollectionBalance.setCourt(totalSettledRateDTO.getCourt());
                tCollectionBalance.setTotalSettledRate(totalSettledRate);
                tCollectionBalance.setDataTime(dataTime);
                tCollectionBalance.setCreateTime(LocalDateTime.now());
                tList.add(tCollectionBalance);
            }

        }


        QueryWrapper<TCollectionBalance> wrapper = new QueryWrapper<>();
        wrapper.eq("data_time",dataTime);
        Integer count = this.getBaseMapper().selectCount(wrapper);
        if (count != null && count > 0){
            // 更新
            log.info("已存在{}的数据",dataTime);
            for (TCollectionBalance tCollectionBalance : tList) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("court",tCollectionBalance.getCourt());
                paramMap.put("totalSettledRate",tCollectionBalance.getTotalSettledRate());
                paramMap.put("dataTime",dataTime);


                this.getBaseMapper().updateTotalRate(paramMap);
            }
        }
        // 插入
        else {
            this.saveBatch(tList);
        }


    }

    /**
     * 获取民商事结案率排名
     * @return
     */
    @Override
    public List<ScoreRankVO> getCivilSettledRateRank() {

        String maxTime = this.getBaseMapper().getMaxTime();
        //获取最大时间的收结存
     List<TCollectionBalance> tCollectionBalanceList =   this.list(new LambdaQueryWrapper<TCollectionBalance>()
                .eq(TCollectionBalance::getDataTime,maxTime)
             .orderByDesc(TCollectionBalance::getCivilSettledRate));
     if (CollectionUtils.isEmpty(tCollectionBalanceList)){
         return null;
     }
        tCollectionBalanceList =   tCollectionBalanceList.stream().filter(item-> (!item.getCourt().contains("高级") && !item.getCourt().contains("中级") && !item.getCourt().equals("合计"))).collect(Collectors.toList());
        List<String> list = new ArrayList<>();
        list.add("乐平市人民法院");
        list.add("景德镇市昌江区人民法院");
        list.add("浮梁县人民法院");
        list.add("景德镇市珠山区人民法院");

        List<ScoreRankVO> scoreRankVOList = new ArrayList<>();

        for (int i=0;i<tCollectionBalanceList.size();i++){
            TCollectionBalance collectionBalance = tCollectionBalanceList.get(i);

            String court = collectionBalance.getCourt();
            if (list.contains(court)){
                ScoreRankVO scoreRankVO = new ScoreRankVO();
                scoreRankVO.setScore(collectionBalance.getCivilSettledRate());
                scoreRankVO.setCourt(collectionBalance.getCourt());
                scoreRankVO.setSort(i+1);
                scoreRankVOList.add(scoreRankVO);
            }
        }
      TCollectionBalance collectionBalance =  tCollectionBalanceList.get(0);
        ScoreRankVO scoreRankVO = new ScoreRankVO();
        scoreRankVO.setCourt(collectionBalance.getCourt());
        scoreRankVO.setScore(collectionBalance.getCivilSettledRate());
        scoreRankVO.setSort(1);
        scoreRankVOList.add(scoreRankVO);
        return scoreRankVOList;
    }

    /**
     * 获取民商事结案率趋势图
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public  Map<String,List<EleScoreRankVO>> getCivilSettledRateRankTrend(String startTime, String endTime) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("startTime",startTime);
        paramMap.put("endTime",endTime);

        List<EleScoreRankVO> eleList = new ArrayList<>();
        //标杆法院
        List<EleScoreRankVO> standartCourtList = this.getBaseMapper().getStandardCourt(paramMap);
        Map<String, List<EleScoreRankVO>> eMap =  standartCourtList.stream().sorted(Comparator.comparing(EleScoreRankVO::getScore).reversed()).collect(Collectors.groupingBy(item->item.getDataTime()));
        for (Map.Entry<String,List<EleScoreRankVO>> entry: eMap.entrySet()){
            eleList.add(entry.getValue().get(0));
        }

        List<EleScoreRankVO> eleScoreRankVOList = this.getBaseMapper().getCivilTrend(paramMap);
        Map<String, List<EleScoreRankVO>> groupMap =  eleScoreRankVOList.stream().sorted(Comparator.comparing(EleScoreRankVO::getScore)).collect(Collectors.groupingBy(item->item.getCourt()));
        Map<String,List<EleScoreRankVO>> map = new HashMap<>();

        for (Map.Entry<String,List<EleScoreRankVO>> entry:groupMap.entrySet()){
            String key = entry.getKey();
            if (key.contains(LfzConstant.CHANGJIANG_COURT) || key.contains(LfzConstant.ZHUSHAN_COURT)
                    || key.contains(LfzConstant.FULIANG_COURT) || key.contains(LfzConstant.LEPU_COURT)){
                map.put(entry.getKey(),entry.getValue());
            }
        }
        map.put("标杆法院",eleList);
        return map;
    }


    /**
     * 获取总结案率排名
     * @return
     */
    @Override
    public List<ScoreRankVO> getTotalSettledRateRank() {
        String maxTime = this.getBaseMapper().getMaxTime();
        //获取最大时间的收结存
        List<TCollectionBalance> tCollectionBalanceList =   this.list(new LambdaQueryWrapper<TCollectionBalance>()
                .eq(TCollectionBalance::getDataTime,maxTime)
                .orderByDesc(TCollectionBalance::getTotalSettledRate));
        if (CollectionUtils.isEmpty(tCollectionBalanceList)){
            return null;
        }
        tCollectionBalanceList =   tCollectionBalanceList.stream().filter(item-> (!item.getCourt().contains("高级") && !item.getCourt().contains("中级") && !item.getCourt().equals("合计"))).collect(Collectors.toList());
        List<String> list = new ArrayList<>();
        list.add("乐平市人民法院");
        list.add("景德镇市昌江区人民法院");
        list.add("浮梁县人民法院");
        list.add("景德镇市珠山区人民法院");

        List<ScoreRankVO> scoreRankVOList = new ArrayList<>();

        for (int i=0;i<tCollectionBalanceList.size();i++){
            TCollectionBalance collectionBalance = tCollectionBalanceList.get(i);

            String court = collectionBalance.getCourt();
            if (list.contains(court)){
                ScoreRankVO scoreRankVO = new ScoreRankVO();
                scoreRankVO.setScore(collectionBalance.getTotalSettledRate());
                scoreRankVO.setCourt(collectionBalance.getCourt());
                scoreRankVO.setSort(i+1);
                scoreRankVOList.add(scoreRankVO);
            }
        }
        TCollectionBalance collectionBalance =  tCollectionBalanceList.get(0);
        ScoreRankVO scoreRankVO = new ScoreRankVO();
        scoreRankVO.setCourt(collectionBalance.getCourt());
        scoreRankVO.setScore(collectionBalance.getTotalSettledRate());
        scoreRankVO.setSort(1);
        scoreRankVOList.add(scoreRankVO);
        return scoreRankVOList;
    }

    /**
     * 获取总结案率趋势图
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public Map<String, List<EleScoreRankVO>> getTotalSettledRateRankTrend(String startTime, String endTime) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("startTime",startTime);
        paramMap.put("endTime",endTime);

        List<EleScoreRankVO> eleList = new ArrayList<>();
        //标杆法院
        List<EleScoreRankVO> standartCourtList = this.getBaseMapper().getTotalStandardCourt(paramMap);
        Map<String, List<EleScoreRankVO>> eMap =  standartCourtList.stream().sorted(Comparator.comparing(EleScoreRankVO::getScore).reversed()).collect(Collectors.groupingBy(item->item.getDataTime()));
        for (Map.Entry<String,List<EleScoreRankVO>> entry: eMap.entrySet()){
            eleList.add(entry.getValue().get(0));
        }

        List<EleScoreRankVO> eleScoreRankVOList = this.getBaseMapper().getTotalTrend(paramMap);
        Map<String, List<EleScoreRankVO>> groupMap =  eleScoreRankVOList.stream().sorted(Comparator.comparing(EleScoreRankVO::getScore)).collect(Collectors.groupingBy(item->item.getCourt()));
        Map<String,List<EleScoreRankVO>> map = new HashMap<>();

        for (Map.Entry<String,List<EleScoreRankVO>> entry:groupMap.entrySet()){
            String key = entry.getKey();
            if (key.contains(LfzConstant.CHANGJIANG_COURT) || key.contains(LfzConstant.ZHUSHAN_COURT)
                    || key.contains(LfzConstant.FULIANG_COURT) || key.contains(LfzConstant.LEPU_COURT)){
                map.put(entry.getKey(),entry.getValue());
            }
        }
        map.put("标杆法院",eleList);
        return map;
    }


}
